﻿using System;
using System.Text;

namespace DevTools.CodeFormatter.Components
{
    public static class Formatter
    {
        public static string Format(string code, int lineDigit, char lineSeperator)
        {
            string[] lines = code.Split(new string[] {Environment.NewLine}, StringSplitOptions.None);

            if (lineDigit == 0)
                lineDigit = lines.Length.ToString().Length;

            int spaceDigit = 0;
            while (lines[0][spaceDigit] == ' ')
                spaceDigit++;

            int index = 1;
            StringBuilder builder = new StringBuilder(lines.Length);
            foreach (string line in lines)
            {
                // 마지막 줄이 빈문자열이면 추가하지 않는다.
                if (index == lines.Length && line == string.Empty)
                    break;

                string formattedLine = FormatLine(index++, line, spaceDigit, lineDigit, lineSeperator);
                
                builder.AppendLine(formattedLine);
            }

            string formattedCode = builder.ToString();
            return formattedCode.Substring(0, formattedCode.Length - 2);
        }

        private static string GetLineNumber(int index, int lineDigit)
        {
            if (lineDigit == 0)
                return string.Empty;
            else if (lineDigit == 1)
                return index.ToString("D1");
            if (lineDigit == 1)
                return index.ToString("D1");
            else if (lineDigit == 2)
                return index.ToString("D2");
            else if (lineDigit == 3)
                return index.ToString("D3");
            else if (lineDigit == 4)
                return index.ToString("D4");
            else if (lineDigit == 5)
                return index.ToString("D5");
            else if (lineDigit == 6)
                return index.ToString("D6");
            else
                return string.Empty;
        }

        private static string FormatLine(int index, string line, int spaceDigit, int lineDigit, char lineSeperator)
        {
            string lineNumber = GetLineNumber(index, lineDigit);

            if (line == String.Empty)
                return lineNumber;
            else if (lineNumber == string.Empty)
                return line.Remove(0, spaceDigit);
            else
                return lineNumber + lineSeperator + line.Remove(0, spaceDigit);
        }
    }
}